<?php
/*
 * @Author: wangzhichao
 * @Date: 2025-01-26 10:04:46
 * @LastEditors: your Name
 * @LastEditTime: 2025-01-26 10:44:39
 * @Description: 
 */
namespace Project;

class WeChat {
    private $appId;
    private $appSecret;
    private $tokenFile = './storage/cache/token_cache.json'; // 缓存文件路径

    public function __construct($appId, $appSecret) {
        $this->appId = $appId;
        $this->appSecret = $appSecret;
    }

    // 获取 access_token
    public function getAccessToken() {
        // 检查缓存是否存在且未过期
        if (file_exists($this->tokenFile)) {
            $data = json_decode(file_get_contents($this->tokenFile), true);
            if ($data['expire_time'] > time()) {
                return $data['access_token'];
            }
        }

        // 请求新的 access_token
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appId}&secret={$this->appSecret}";
        $response = file_get_contents($url);
        $data = json_decode($response, true);

        if (isset($data['access_token'])) {
            // 保存到缓存
            file_put_contents($this->tokenFile, json_encode([
                'access_token' => $data['access_token'],
                'expire_time' => time() + $data['expires_in'] - 200 // 提前 200 秒刷新
            ]));
            return $data['access_token'];
        }

        return null;
    }

    // 获取 jsapi_ticket
    public function getJsApiTicket() {
        $accessToken = $this->getAccessToken();
        if (!$accessToken) {
            return null;
        }

        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$accessToken&type=jsapi";
        $response = file_get_contents($url);
        $data = json_decode($response, true);

        return isset($data['ticket']) ? $data['ticket'] : null;
    }

    // 生成 JS-SDK 配置
    public function generateJsSdkConfig($url) {
        $ticket = $this->getJsApiTicket();
        if (!$ticket) {
            return null;
        }

        $timestamp = time();
        $nonceStr = $this->generateNonceStr();

        $string = "jsapi_ticket=$ticket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
        $signature = sha1($string);

        return [
            'appId' => $this->appId,
            'timestamp' => $timestamp,
            'nonceStr' => $nonceStr,
            'signature' => $signature,
            'url' => $url
        ];
    }

    // 生成随机字符串
    private function generateNonceStr($length = 16) {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $str = '';
        for ($i = 0; $i < $length; $i++) {
            $str .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        return $str;
    }
}
